#include "pictranscoderapi.h"
#include <dlfcn.h>
#include <cstdio>
#include "errno_tcapi.h"

#define CHECK_DLERROR(errCode)  \
    do {                  \
        char *e = dlerror();                  \
        if ((e) != nullptr) { \
            printf("dl error: %s\n", (e)); \
            return (errCode);                  \
        }   \
    } while(0)


#define SET_FUNC(handle, pFunc, funcDef, name) \
    do {                                       \
             (pFunc) = (funcDef)dlsym((handle), (name)); \
             CHECK_DLERROR(ERR_LIB_TCAPI_NO_FUNC);    \
    }while(0)


PicTransCoderApi::PicTransCoderApi() {
    pHandle = nullptr;
}

PicTransCoderApi::~PicTransCoderApi() {
    if (pHandle != nullptr)
    {
        printf("~PicTransCoderApi\n");
        dlclose(pHandle);
    }
}

PicTransCoderApi *PicTransCoderApi::GetInstance() {
    static PicTransCoderApi g_picTranscoderApi;
    return &g_picTranscoderApi;
}

int PicTransCoderApi::Init() {
    if (pHandle == nullptr)
    {
        pHandle = dlopen("libPictranscoder.so", RTLD_LAZY | RTLD_LOCAL);
        CHECK_DLERROR(ERR_LIB_PICTRANSCODE);
    }

    SET_FUNC(pHandle, TranscoderOpen, tcapi_func_def::PTranscodeOpen, "TranscodeOpen");
    SET_FUNC(pHandle, TranscoderClose, tcapi_func_def::PTranscodeClose , "TranscodeClose");
    SET_FUNC(pHandle, TranscoderPutTask, tcapi_func_def::PTranscodePutTask , "TranscodePutTask");
    SET_FUNC(pHandle, TranscoderWaitTaskFinish, tcapi_func_def::PTranscodeWaitTaskFinish , "TranscodeWaitTaskFinish");

    return 0;
}
